package cn.jingyuan.owl.enums.spring;

import cn.jingyuan.owl.enums.core.EnumString;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

/**
 * 自定义 {@link String} 类型枚举转换
 */
public class EnumStringConverter implements ConverterFactory<String, EnumString> {

    @Override
    public <T extends EnumString> Converter<String, T> getConverter(Class<T> targetType) {
        return new StringToEnum(targetType);
    }

    private class StringToEnum<T extends EnumString> implements Converter<String, T> {

        private final Class clazz;

        public StringToEnum(Class<T> targetType) {
            clazz = targetType;
        }

        @Override
        public T convert(String source) {
            Enum value = EnumString.valueOf(source, clazz);

            if (null == value) {
                return null;
            }
            return (T) value;
        }

    }

}
